import axios from "axios";
import {Notify} from 'vant';
import store from "@/store";

console.info(process)
// const BASE_URL =  process.env.NODE_ENV === ("development") ? process.env.VUE_APP_URL : window.__config.VUE_APP_URL;
// 本工程中axios使用，均通过其API构建请求，可参考https://www.kancloud.cn/yunye/axios/234845
const service = axios.create({
  retry: 2,
  baseURL: process.env.NODE_ENV === "development"||"mock" ?
    process.env.VUE_APP_BASE_API : window.__config.VUE_APP_BASE_API,
  timeout: 5000, // request timeout,
  retryDelay: 1000
});
// request interceptor
service.interceptors.request.use(
  async request => {
    request.headers["Access-Control-Allow-Origin"] = "*";
    //判断是否存在token，如果存在将每个页面header都添加token
    var tmpToken = store.getters.token
    if (tmpToken) {
      request.headers["Authorization"] = "Bearer " + tmpToken.access_token;
    }
    return request;
  },
  error => {
    Notify('通知内容--request--error');
    // 请求发生错误
    console.log("request interceptor error"); // for debug
    Promise.reject(error);
  }
);
// response interceptor
service.interceptors.response.use(
  async response => {
    /**
     * Status Code: 200
     */
    const res = response.data;
    if (res.code !== 1 && res.code !== 200) {
      if (store.getters.token) {
        Notify('1==200---token-通知内容');
        console.info("else-------------怎么处理？");
      } else {
        // 没有登录态
        Notify('1!==2-----notoken--通知内容');
        console.info("notoken dengchu else-------------");
        window.location.href = `${baseURL}/login`;
      }
    } else {
      return res.data;
    }
  },
  async error => {
    console.info("error async------------------");
    if (error && error.response) {
      switch (error.response.status) {
        case 401: // 登陆失效
          store.dispatch('FedLogOut').then(() => {
            window.location.href = `/${baseURL}/#/login`;
          })
          console.info("dengchu else-------------");
          Notify(error.message);
          break;
        case 500:
          console.info(500);
          error.message = "服务器错误(500)";
          Notify(error.message);
          break;
        default:
          console.info("default----------");
          Notify(error.message);
          break;
      }
    } else if (error) {
      Notify(error.message);
      console.info(error);
      console.info("no response----------");
    }
    return Promise.reject(error);
  }
);

export default service;
